<?php

class App_Methods_Request_GetUserGroupApplications {

  /**
   *
   * @var App_Methods_Data_App
   */
  public $app;

  public function __construct($params) {
    $this->app = new App_Methods_Data_App($params->app);
  }

  public function process() {
    if (!Core_Auth::getInstance()->getUser()->isAdmin())
    	throw new App_Exception_App(4000);
    
    $applications = ApplicationsQuery::create()
    ->useApplicationDataSetsQuery()
    	->filterByStatus(ApplicationDataSets::STATUS_ACCEPTED)
    	->orderByLastModified()
    ->endUse()
    ->find();
    
    
    $userGroupsPropel = UserGroupsQuery::create()
    	->useUserGroupApplicationsQuery(null, Criteria::LEFT_JOIN)
    	->endUse()
    	->find();
    
    $userGroups = array();
    foreach ($userGroupsPropel as $userGroup) {
    	$userGroups[$userGroup->getId()] = $userGroup;
    }
    
    $response = new App_Methods_Response_GetUserGroupApplications(true);
    $lang = Core_Core::getInstance()->getApp()->lang;
    foreach ($applications as $application) {
    	$currentSet = null;
    	foreach ($application->getApplicationDataSetss() as $applicationDataSet) {
    		if ($currentSet == null) {
    			$currentSet = $applicationDataSet;
    			continue;
    		}
    		if ($currentSet->getLastModified() < $applicationDataSet->getLastModified())
    			$currentSet = $applicationDataSet;
    	}
    	if ($lang == 'en')
    		$response->addApplication($currentSet->getNameEn());
    	else
    		$response->addApplication($currentSet->getName());
    }
    foreach ($userGroups as $userGroup) {
    	$group = new App_Methods_Data_UserGroupApplications($userGroup);
    	$userGroupApplicationsId = array();
    	foreach ($userGroup->getUserGroupApplicationss() as $userGroupApplication) {
    		$userGroupApplicationsId[] = $userGroupApplication->getApplicationId();
    	}
    	foreach ($applications as $application) {
    		$application = new App_Methods_Data_ApplicationChecked($application->getId(), in_array($application->getId(), $userGroupApplicationsId));
    		$group->addApplication($application);
    	}
    	$response->addGroup($group);
    }
    
    return $response;
  }

}